package com.raysdata.smartcity.dao.sys;

import com.raysdata.smartcity.HelperClazz;
import com.raysdata.smartcity.dao.RzBaseDao;
import com.raysdata.smartcity.dto.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by liux on 2016/10/14.
 */
@Component
public class UserDao {
    Log log = LogFactory.getLog(UserDao.class);
    @Autowired
    private RzBaseDao rzBaseDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 登录验证
     * @param loginName
     * @param pwd
     * @return
     */
    public User login(String loginName,String pwd){
        final String sql ="select * from ss_user where login_name= ? and password = ? and status ='0'";
        List<User> user = rzBaseDao.query(sql,User.class,new Object[]{loginName,pwd});
        return user.isEmpty() ? null : user.get(0);
    }

    /**
     * 修改密码
     * @param user
     */
    public int updPwd(User user) {
        final String sql = "update ss_user set password = :password where user_id = :user_id";
        return rzBaseDao.update(sql,user);
    }

    /**
     * 根据用户ID查询用户
     * @param user_id
     * @return
     */
    public User getUserById(String user_id) {
        final String sql ="select user_id,login_name,`password`,user_name,phone,email,org_id,org_name,status,cdate,cperson,remark,permission,id_card from ss_user where user_id = ?";
        List<User> user = rzBaseDao.query(sql,User.class,new Object[]{user_id});
        return user.isEmpty() ? null : user.get(0);
    }

    /**
     * 用户查询列表
     * @param page
     * @param count
     * @param user
     * @return
     */
    public List<User> queryUsers( Integer page, Integer count,User user) {
        StringBuilder sb=new StringBuilder();
        sb.append(" select u.*,a.value,o.name as dept_name from ss_attr a,ss_user u left join ss_org o on o.org_id=u.org_id where u.status=0  ");
        sb.append(" and u.permission=a.code ");
//        sb.append(" and o.org_id=u.org_id  ");
        if (!HelperClazz.isEmpty(user.getUser_name())) {
            sb.append(" and u.user_name like '%" + user.getUser_name() + "%' ");
        }
        if (!HelperClazz.isEmpty(user.getLogin_name())) {
            sb.append(" and u.login_name like '%" + user.getLogin_name() + "%' ");
        }
        if (!HelperClazz.isEmpty(user.getOrg_name())) {
            sb.append(" and o.name like '%" + user.getOrg_name() + "%' ");
        }
        sb.append("  order by u.cdate desc");

        Object[] params = new Object[0];
        int index = 0;
        Object[] paramsEnd = new Object[index];
        System.arraycopy(params, 0, paramsEnd, 0, index);
        if (page <= 0 || count <= 0) {//all
            return rzBaseDao.query(sb.toString(), User.class, paramsEnd);
        } else {
            count = (count > 0) ? count : Integer.MAX_VALUE;
            return rzBaseDao.queryBySlice(sb.toString(), User.class, paramsEnd, page, count);
        }
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    public int addUser(User user) {
        try {

            final StringBuilder sql = new StringBuilder();
            sql.append("insert into ss_user  ( user_id,  ");
            sql.append("login_name, ");
            sql.append("password,");
            sql.append("user_name,");
            sql.append("phone,");
            sql.append("email,");
            sql.append("org_id, ");
            sql.append(" org_name,");
            sql.append("remark,");
            sql.append("status,");
            sql.append("cdate,");
            sql.append("permission,");
            sql.append("id_card,");
            sql.append("cperson )   ");

            sql.append("values(");
            sql.append(" '" + UUID.randomUUID().toString().trim().replaceAll("-", "") + "',");
            sql.append(":login_name,");
            sql.append(":password,");
            sql.append(":user_name,");
            sql.append(":phone,");
            sql.append(" :email,");
            sql.append(":org_id,");
            sql.append(":org_name,");
            sql.append(":remark,");
            sql.append("0,");
            sql.append("now(), ");
            sql.append(":permission,");
            sql.append(":id_card,");
            sql.append(":cperson");
            sql.append(")");
            rzBaseDao.insert(sql.toString(), user);
            return 0;
        } catch (Exception e) {
            return -1;
        }

    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    public int updUser(User user) {
        try {
            StringBuilder sql = new StringBuilder();
            sql.append("UPDATE ss_user                         ");
            sql.append("	SET permission=:permission,user_name=:user_name,phone=:phone,email=:email,org_id=:org_id,org_name=:org_name,remark=:remark,id_card=:id_card   ");
            sql.append("	WHERE user_id=:user_id");
            rzBaseDao.update(sql.toString(), user);
            return 0;

        } catch (Exception e) {
            return -1;
        }
    }

    /**
     *根据ID删除用户
     * @param user
     */
    public int delUserById(User user){
        String sql = "update ss_user set status=1  where user_id=:user_id";
        return rzBaseDao.update(sql,user);
    }

    /**
     * 概括登录名获取用户信息
     * @param login_name
     * @return
     */
    public User getUserByLoginName(String login_name){
        final String sql ="select * from ss_user where login_name = ? and status=0";
        List<User> user = rzBaseDao.query(sql,User.class,new Object[]{login_name});
        return user.isEmpty() ? null : user.get(0);
    }

    public User getUserByLoginNameAndNot(String login_name){
        final String sql ="select * from ss_user where login_name = ? ";
        List<User> user = rzBaseDao.query(sql,User.class,new Object[]{login_name});
        return user.isEmpty() ? null : user.get(0);
    }

    /**
     * 用户配置角色
     * @param user_id
     * @param role_id
     */
    public void configRoles(String user_id,String role_id){
        String sql =  " insert into ss_user_role(id,user_id,role_id) values('" + UUID.randomUUID().toString().trim().replaceAll("-", "") + "','"+user_id+"','"+role_id+"') ";
        jdbcTemplate.execute(sql);
    }

    /**
     * 获取用户所有角色
     * @param user_id
     * @return
     */
    public List<Map<String,Object>> queryRoleByUserId(String user_id) {
        String sql =" select ur.role_id as roleId,r.name as roleName from ss_user_role ur LEFT JOIN  ss_role r ON ur.role_id=r.role_id  where user_id ='"+user_id+"'";
        List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
        list=jdbcTemplate.queryForList(sql);
        return list;
    }

    /**
     *清空用户角色
     * @param user_id
     */
    public void delUserRoles(String user_id){
        String sqlu = "delete from  ss_user_role where user_id= '"+user_id+"'";
        jdbcTemplate.execute(sqlu);
    }
    public int updateOrg(User user){
        String sql="update ss_user set org_id=:org_id,org_name=:org_name where user_id=:user_id ";
        return rzBaseDao.update(sql,user);
    }
    public int updatePm(User user){
        String sql="update ss_user set permission=:permission where user_id=:user_id ";
        return rzBaseDao.update(sql,user);
    }
    public int getUserCountByOrgCode(String code){
        String sql="SELECT COUNT(*) FROM ss_user u,ss_org o WHERE u.org_id=o.org_id AND o.org_code LIKE '"+code+"%' AND u.status='0'";
        return jdbcTemplate.queryForObject(sql.toString(), Integer.class);
    }

    /**
     * 根据LDAP数据修改用户
     * @param user
     * @return
     */
    public int updUserByLdap(User user){
        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE ss_user                         ");
        sql.append("	SET user_name=:user_name,phone=:phone,email=:email,ldap_dn=:ldap_dn,ldap_udate=now()  ");
        sql.append("	WHERE login_name=:login_name and login_name!='admin' and login_name!='administrator'");
        return rzBaseDao.update(sql.toString(), user);
    }

    /**
     * 根据LDAP数据删除用户
     * @param login_name
     * @return
     */
    public int delUserByLdap(String login_name){
        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE ss_user                         ");
        sql.append("	SET status='1'  ");
        sql.append("	WHERE login_name not in("+login_name+") and login_name!='admin' and login_name!='administrator'");
        jdbcTemplate.execute(sql.toString());
        return 0;
    }

    /**
     * 根据LDAP数据新增用户
     * @param user
     * @return
     */
    public int addUserByLdap(User user) {
        final StringBuilder sql = new StringBuilder();
        sql.append("insert into ss_user  ( user_id,  ");
        sql.append("login_name, ");
        sql.append("password,");
        sql.append("user_name,");
        sql.append("phone,");
        sql.append("email,");
        sql.append("cdate,");
        sql.append("ldap_udate,");
        sql.append("ldap_dn,");
        sql.append("permission,");
        sql.append("cperson )   ");

        sql.append("values(");
        sql.append(" '" + UUID.randomUUID().toString().trim().replaceAll("-", "") + "',");
        sql.append(":login_name,");
        sql.append(":password,");
        sql.append(":user_name,");
        sql.append(":phone,");
        sql.append(" :email,");
        sql.append("now(), ");
        sql.append("now(),");
        sql.append(":ldap_dn,");
        sql.append(":permission,");
        sql.append("'LDAP'");
        sql.append(")");
        rzBaseDao.insert(sql.toString(), user);
        return 0;
    }

    /**
     * 根据User数据新增ActivitiUser
     * @param
     * @return
     */
    public int addActivitiByUser(){
        String sql="insert into act_id_user (ID_,REV_,EMAIL_)" +
                "  select su.login_name,'1',su.email from ss_user su where su.login_name not in(select au.ID_ from act_id_user au) " +
                "and su.login_name!='admin' and su.login_name!='administrator'";
        jdbcTemplate.execute(sql.toString());
        return 0;
    }
    /**
     * 根据User数据修改ActivitiUser
     * @param
     * @return
     */
    public int updActivitiByUser(){
        String sql="update act_id_user au,ss_user su set au.EMAIL_=su.email where au.ID_=su.login_name";
        jdbcTemplate.execute(sql.toString());
        return 0;
    }

    /**
     * 根据角色和组织机构获取用户
     * @param rolename
     * @param org
     * @return
     */
    public List<User> getUserByOrgAndRole(String rolename,String org){
       // String sql="select u.* from ss_user u LEFT JOIN ss_user_role ur ON u.user_id=ur.user_id LEFT JOIN ss_role r ON r.role_id=ur.role_id LEFT JOIN ss_org o ON u.org_id=o.org_id  where r.`name`=? and o.org_code like '%"+org+"%' ";
        String sql="select u.* from ss_user u LEFT JOIN ss_user_role ur ON u.user_id=ur.user_id LEFT JOIN ss_role r ON r.role_id=ur.role_id LEFT JOIN ss_org o ON u.org_id=o.org_id  where r.`code`=? and o.org_code like '%"+org+"%' ";
        List<User> users = rzBaseDao.query(sql,User.class,new Object[]{rolename});
        return users;
    }

}